<?php

namespace App\Models\Traits;

use App\User;
use Illuminate\Support\Facades\Auth;

trait Favour
{
    public function favours()
    {
        return $this->morphToMany(User::class, 'favour', 'favour');
    }

//切换点赞
    public function favour()
    {
        $method = $this->isFavour ? 'detach' : 'attach';
        //禁止自己给自己点赞
        if(user('id')==$this->user_id){
            return back()->with('danger','不可以给自己点赞');
        }
        $this->favours()->$method([Auth::id()], ['site_id' => site()['id'], 'module_id' => module()['id']]);
        if (isset($this->favour_count)) {

            $this->favour_count = $this->favours()->count();
        }

        $this->save();

    }

    public function getIsFavourAttribute()
    {
        return $this->favours()->wherePivot('user_id', user('id'))->exists();
    }
}
